package com.example.wm.SanWar.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.SanWar.entity.Allies;
import com.example.wm.SanWar.mapper.GameUserMapper;
import com.example.wm.SanWar.service.AlliesService;
import com.example.wm.common.BaseContext;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.SanWar.entity.AlliesandUser;
import com.example.wm.SanWar.entity.GameUser;
import com.example.wm.SanWar.mapper.AlliesandUserMapper;
import com.example.wm.SanWar.service.AlliesRecodeSheetService;
import com.example.wm.SanWar.service.GameUserService;
import com.example.wm.utils.TsyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/GameUserController")
public class GameUserController {
    @Resource
    private GameUserService gameUserService;
    @Resource
    private GameUserMapper gameUserMapper;
    @Resource
    private AlliesandUserMapper alliesandUserMapper;
    @Resource
    private AlliesService alliesService;
    @Resource
    private AlliesRecodeSheetService alliesRecodeSheetService;
    @Resource
    private TsyUtils tsyUtils;
//    @Transactional
    @PostMapping("/Insert")
    public Result Insert(@RequestBody GameUser gameUser) {
        LambdaQueryWrapper<GameUser> lq=new LambdaQueryWrapper<>();
        lq.eq(GameUser::getName,gameUser.getName());
     long n=   gameUserService.count(lq);
     GameUser g=gameUserService.getOne(lq);
     if(n>0){
         Long id= Long.valueOf(g.getId());
         BaseContext.setCurrentId(id);
         alliesRecodeSheetService.insertList(gameUser.getName(),"进入小程序");
//         更新wxid
         g.setWxid(gameUser.getWxid());
         gameUserService.updateById(g);
//         查询有没有数据  提供给loginuserinfo
         LambdaQueryWrapper<AlliesandUser> aulq=new LambdaQueryWrapper<>();
         aulq.eq(AlliesandUser::getName,gameUser.getName());
         aulq.ne(AlliesandUser::getStatus,"已退盟");
         aulq.ne(AlliesandUser::getStatus,"已拉黑");

         Long na=  alliesandUserMapper.selectCount(aulq);
         if(na>0){
             return ResultData.success("已有数据",g.getId());

         }else{
             return ResultData.success(g.getId());

         }
     }else{

//         gameUser.setRegestertime(tsyUtils.getnowtime());
         gameUser.setWxid(gameUser.getWxid());
         boolean b=    gameUserService.save(gameUser);
         if(b){
             Long id= Long.valueOf(gameUser.getId());
             BaseContext.setCurrentId(id);
             alliesRecodeSheetService.insertList(gameUser.getName(),"创建用户并且进入小程序");
             return ResultData.success(id);
         }else{
             return ResultData.success("失败");

         }
     }



    }

    @Transactional
    @PostMapping("/updatename")
    public Result updatename(@RequestBody JSONObject jsonObject) {
        LambdaQueryWrapper<GameUser> lq=new LambdaQueryWrapper<>();
        lq.eq(GameUser::getName,jsonObject.getString("name"));

        long n=   gameUserMapper.selectCount(lq);
        System.out.println("姓名："+n);
        GameUser gameUser=new GameUser();
        gameUser.setId(jsonObject.getInteger("id"));
        gameUser.setName(jsonObject.getString("name"));

        if(n==1){
            return ResultData.error(403,"用户名已存在");
        }else{
            boolean b=    gameUserService.updateById(gameUser);
            LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
            lqa.eq(AlliesandUser::getUserid,gameUser.getId());
            lqa.eq(AlliesandUser::getStatus,"在盟");

             AlliesandUser a=     alliesandUserMapper.selectOne(lqa);
             a.setName(gameUser.getName());
            alliesandUserMapper.updateById(a);
//            把创建人也修改 盟
            LambdaQueryWrapper<AlliesandUser> lqa2=new LambdaQueryWrapper<>();
            lqa2.eq(AlliesandUser::getCreatename,jsonObject.getString("beforename"));
            lqa2.eq(AlliesandUser::getTmid,jsonObject.getString("tmid"));

            List<AlliesandUser> aulist=alliesandUserMapper.selectList(lqa2);
            System.out.println("aulist:"+aulist);

            if(!aulist.isEmpty()){
                for(AlliesandUser au:aulist){
                    au.setCreatename(jsonObject.getString("name"));
                     alliesandUserMapper.updateById(au);
                }
            }
            LambdaQueryWrapper<Allies> lqaa=new LambdaQueryWrapper<>();
            lqaa.eq(Allies::getCreatename,jsonObject.getString("beforename"));
            lqaa.eq(Allies::getId,jsonObject.getString("tmid"));
            List<Allies> aulistaa=alliesService.list(lqaa);
            System.out.println("aulistaa:"+aulistaa);

            if(!aulistaa.isEmpty()){
                for(Allies au:aulistaa){
                    au.setCreatename(jsonObject.getString("name"));
                    alliesService.updateById(au);
                }
            }

                     alliesRecodeSheetService.insertList(gameUser.getName(),"修改了游戏名");


                 return ResultData.success("修改成功");

        }



    }


    @Transactional
    @PostMapping("/updatenamenotmz")
    public Result updatenamenotmz(@RequestBody JSONObject jsonObject) {
        LambdaQueryWrapper<GameUser> lq=new LambdaQueryWrapper<>();
        lq.eq(GameUser::getName,jsonObject.getString("name"));

        long n=   gameUserMapper.selectCount(lq);
        System.out.println("姓名："+n);
        GameUser gameUser=new GameUser();
        gameUser.setId(jsonObject.getInteger("id"));
        gameUser.setName(jsonObject.getString("name"));
        if(n==1){
            return ResultData.error(403,"用户名已存在");
        }else{
            boolean b=    gameUserService.updateById(gameUser);
            LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
            lqa.eq(AlliesandUser::getName,jsonObject.getString("beforename"));
            AlliesandUser au=alliesandUserMapper.selectOne(lqa);
            au.setName(jsonObject.getString("name"));
            alliesandUserMapper.updateById(au);

            if(b){
                return ResultData.success("修改成功");

            }else{
                return ResultData.success(b);

            }
        }
    }
    @PostMapping("/find")
    public Result findss(@RequestBody JSONObject jsonObject) {
//        LambdaQueryWrapper<GameUser> gul=new LambdaQueryWrapper<>();
//
//        List<GameUser> ll= gameUserService.list(gul);
//        for(GameUser gull :ll){
//            gull.setMonthlysuattribute("月卡");
//            gameUserService.updateById(gull);
//        }

        LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
        lqa.eq(AlliesandUser::getUserid,jsonObject.getInteger("id"));
//        lqa.ne(AlliesandUser::getStatus,"已退盟");
//        lqa.ne(AlliesandUser::getStatus,"已拉黑");
        lqa.in(AlliesandUser::getStatus,"在盟","待审核");
        AlliesandUser a=alliesandUserMapper.selectOne(lqa);
         // System.out.println("AlliesandUsers:"+a);
        LambdaQueryWrapper<GameUser> lg=new LambdaQueryWrapper<>();
        lg.eq(GameUser::getId,jsonObject.getInteger("id"));
        GameUser gu=gameUserService.getOne(lg);

        ArrayList<Object> alist=new ArrayList<>();
        alist.add(a);
        alist.add(gu);
        System.out.println(alist+"alist");

        return ResultData.success(alist);
    }
//    login openid
    @Transactional
    @GetMapping("/screateNewapp")
    //openid
    public Result screateNewapp( @RequestParam("code") String code){
        System.out.println(code+":code");
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        String openid = null;
        String newAccessTockenUrl="https://api.weixin.qq.com/sns/jscode2session?appid=wxff7ee9494b09e7e6&secret=eeb8f16926dc90deec33ce5a95486209&js_code="+code+"&grant_type=authorization_code";
        try {
            //创建get请求
            HttpGet httpGet = new HttpGet(newAccessTockenUrl);
            response = httpClient.execute(httpGet);
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);
            //转换成对象，好把需要的字段对应的值拿出来
            JSONObject jsonObject = JSONObject.parseObject(resultDemo);
            System.out.println("12122121"+jsonObject);
            openid= jsonObject.getString("openid");
//            return  ResultData.success("操作成功",openid);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ResultData.success("操作成功",openid);
    }

    @Transactional
    @PostMapping("/findbywxid")
    public Result findbywxid(@RequestBody GameUser gameUser){
        LambdaQueryWrapper<GameUser> lqa=new LambdaQueryWrapper<>();
        lqa.eq(GameUser::getWxid,gameUser.getWxid());
        List<GameUser> a=gameUserService.list(lqa);
        return ResultData.success(a);

    }
}
